﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using Table= FCNS.Data.Table;
using DoubleH.Utility;
using DoubleH;
using DoubleH.Utility.IO;
using DoubleH.Utility.Configuration;
using FCNS.Data;
using System.Collections.ObjectModel;

namespace ProductS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Table.ProductS order = null;
        string imageFile = string.Empty;//只有点击按钮选择图片之后,才赋值给它,防止重复的更新图片文件到服务器
        bool sendImageFile = false;

        public MainWindow()
        {
            InitializeComponent();
        }

        public void Init(Table.ProductS obj)
        {
            order = obj ?? new Table.ProductS();
            Table.SysConfig sysConfig = Table.SysConfig.SysConfigParams;

            uCGroupS1.Init(Table.GroupS.EnumFlag.商品分类);
            uCUniqueSBrand.Init(Table.UniqueS.EnumFlag.品牌);
            uCUniqueSPlace.Init(Table.UniqueS.EnumFlag.产地);
            uCUniqueSUnit.Init(Table.UniqueS.EnumFlag.计量单位);

            uCUniqueSUnit.SelectedObjectId = order.UnitId;
            uCGroupS1.SelectedObjectId = order.GroupSId;
            uCUniqueSBrand.SelectedObjectId = order.BrandId;
            uCUniqueSPlace.SelectedObjectId = order.PlaceId;

            textBoxName.Text = order.Name;
            textBoxCode.Text = order.Code;
            textBoxBarcode.Text = order.Barcode;
            textBoxStandard.Text = order.Standard;
            textBoxModel.Text = order.Model;
            textBoxNote.Text = order.Note;

            bool isUsed = order.IsUsed();
            InitOrderFlag(isUsed);
            InitWuLiao(isUsed);
            ConfigControlAfterChecked();

            checkBoxDiscount.IsChecked = order.IsDiscount;
            checkBoxScore.IsChecked = order.IsScore;

            integerUpDownBaoXiu.Value = (int)order.BaoXiu;
            doubleUpDownDiscount.Value = order.Discount;

            doubleUpDownPurchasePrice.Value = order.PurchasePrice;
            doubleUpDownWholesalePrice1.Value = order.WholesalePrice1;
            doubleUpDownWholesalePrice2.Value = order.WholesalePrice2;
            doubleUpDownWholesalePrice3.Value = order.WholesalePrice3;
            doubleUpDownWholesalePrice4.Value = order.WholesalePrice4;
            doubleUpDownWholesalePrice5.Value = order.WholesalePrice5;
            doubleUpDownPosPrice.Value = order.PosPrice;
            doubleUpDownVip.Value = order.VipPrice;

            //仓库
            SqlFunction sqlf = new SqlFunction();
            dataGridStoreS.ItemsSource = sqlf.GetStoreSProperty(order.Id);
            //图片
            if (order.Id != -1 && !string.IsNullOrEmpty(order.UploadFile))
            {
                string path = TransferFiles.GetFile(new FileFormat() { TableName = "ProductS", FileName = order.UploadFile, FileFlag = FileType.请求文件 });
                if (!string.IsNullOrEmpty(path))
                    image1.Source = new BitmapImage(new Uri(path));
            }

            textBoxName.Focus();
            InitEvent();
        }

        private void InitEvent()
        {
            buttonImage.Click += (ss, ee) => SelectImg();
            image1.MouseLeftButtonUp += (ss, ee) => RemoveImg(ee);
            checkBoxIsPurchase.Click += (ss, ee) => ConfigControlAfterChecked();
            checkBoxIsSales.Click += (ss, ee) => ConfigControlAfterChecked();
            checkBoxCombo.Click += (ss, ee) => ConfigControlAfterChecked();
            checkBoxNoKuCun.Click += (ss, ee) => ConfigControlAfterChecked();
            buttonSave.Click += (ss, ee) => Save();
        }

        private void RemoveImg(MouseButtonEventArgs ee)
        {
            image1.Source = null;
            sendImageFile = false;
        }

        private void SelectImg()
        {
            imageFile = FileTools.GetFile(true, ".jpg", ".bmp", ".png", ".gif");
            if (!string.IsNullOrEmpty(imageFile))
            {
                image1.Source = new BitmapImage(new Uri(imageFile));
                sendImageFile = true;
            }
        }

        private void ConfigControlAfterChecked()
        {
            if (checkBoxNoKuCun.IsChecked.Value)
                checkBoxIsPurchase.IsChecked = false;

            bool p = checkBoxIsPurchase.IsChecked.Value;
            tabItemStore.Visibility = p ? Visibility.Visible : Visibility.Collapsed;
            tabItemPurchase.Visibility = p ? Visibility.Visible : Visibility.Collapsed;

            bool s = checkBoxIsSales.IsChecked.Value;
            tabItemSale.Visibility = s ? Visibility.Visible : Visibility.Collapsed;
            tabItemDiscount.Visibility = s ? Visibility.Visible : Visibility.Collapsed;

            if (!p && !s)
                tabControl1.Visibility = Visibility.Hidden;
            else
            {
                tabControl1.Visibility = Visibility.Visible;
                tabControl1.SelectedIndex = p ? 0 : 2;
            }

            tabItemCombo.Visibility = checkBoxCombo.IsChecked.Value ? Visibility.Visible : Visibility.Collapsed;
        }

        private void InitOrderFlag(bool isUsed)
        {
            if (isUsed)
            {
                switch (order.Flag)
                {
                    case Table.ProductS.EnumFlag.免库存:
                        checkBoxIsPurchase.IsEnabled = false;
                        checkBoxIsSales.IsEnabled = false;
                        checkBoxCombo.IsEnabled = false;
                        checkBoxNoKuCun.IsEnabled = false;
                        break;

                    case Table.ProductS.EnumFlag.可采购:
                    case Table.ProductS.EnumFlag.可销售:
                    case Table.ProductS.EnumFlag.可销售和可采购:
                        checkBoxNoKuCun.IsEnabled = false;
                        checkBoxCombo.IsEnabled = false;
                        break;
                }
            }

            switch (order.Flag)
            {
                case Table.ProductS.EnumFlag.免库存:
                    checkBoxNoKuCun.IsChecked = true;
                    checkBoxIsSales.IsChecked = true;
                    break;

                case Table.ProductS.EnumFlag.可采购: checkBoxIsPurchase.IsChecked = true; break;
                case Table.ProductS.EnumFlag.可销售: checkBoxIsSales.IsChecked = true; break;
                case Table.ProductS.EnumFlag.可销售和可采购:
                    checkBoxIsPurchase.IsChecked = true;
                    checkBoxIsSales.IsChecked = true;
                    break;
            }

            checkBoxIsPurchase.IsEnabled = Table.SysConfig.SysConfigParams.UsePurchaseOrderS;
            checkBoxIsSales.IsEnabled = Table.SysConfig.SysConfigParams.UseSalesOrderS;
            checkBoxVisible.IsChecked = order.Enable == Table.ProductS.EnumEnable.停用 ? true : false;
        }

        private void InitWuLiao(bool isUsed)
        {
            if (order.IsWuLiao)
            {
                checkBoxCombo.IsChecked = true;
                if (isUsed)
                {
                    checkBoxNoKuCun.IsEnabled = false;
                    checkBoxCombo.IsEnabled = false;
                    productSListInfoWuLiao.ShowBodyContexMenu = false;
                }
                else
                    productSListInfoWuLiao.ShowBodyContexMenu = true;
            }

            //productSListInfoWuLiao.AbsQuantity = true;
            productSListInfoWuLiao.MustHasStoreS = false;
            productSListInfoWuLiao.Init(DoubleHConfig.UserConfig.GetUserUIparams(DataTableText.物料清单商品编辑));
            productSListInfoWuLiao.CanUserAddRows = false;
            productSListInfoWuLiao.ItemsSource = order._WuLiaoQingDan;
            productSListInfoWuLiao.ShowBottom = false;
            productSListInfoWuLiao.CanNegativeSales = true;
            productSListInfoWuLiao.IsReadOnly = !checkBoxCombo.IsEnabled;//如果物料清单已经有出入库记录,就不能更改清单内容,也不可以修改数量.
            productSListInfoWuLiao.DataGrid.GetColumn("_TempPrice").Visibility =
                ((order.Flag != Table.ProductS.EnumFlag.可销售 &&
                order.Flag != Table.ProductS.EnumFlag.免库存) ? Visibility.Visible : Visibility.Collapsed);

            productSListInfoWuLiao.TempPriceEdited += (ee) => CheckPercent(ee);
        }

        private void CheckPercent(DataGridCellEditEndingEventArgs ee)
        {
            TextBox tb = ee.EditingElement as TextBox;
            if (tb == null)
                return;

            double d = Convert.ToDouble(tb.Text);
            if (d > 1)
                d = 1;
            else if (d < 0)
                d = 0;

            tb.Text = d.ToString();
        }

        private void Save()
        {
            if (order.BarcodeIsExists(textBoxBarcode.Text) && MessageWindow.Show("", "条形码已被其它商品使用，是否继续？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            Table.ProductS.EnumFlag flag = Table.ProductS.EnumFlag.可销售和可采购;

            if (checkBoxCombo.IsChecked.Value)
                order.IsWuLiao = true;
            else
            {
                order.IsWuLiao = false;
                order._WuLiaoQingDan.Clear();
            }
            if (checkBoxNoKuCun.IsChecked.Value)
                flag = Table.ProductS.EnumFlag.免库存;
            else if (checkBoxIsPurchase.IsChecked == true && checkBoxIsSales.IsChecked == false)
                flag = Table.ProductS.EnumFlag.可采购;
            else if (checkBoxIsPurchase.IsChecked == false && checkBoxIsSales.IsChecked == true)
                flag = Table.ProductS.EnumFlag.可销售;

            order.Flag = flag;

            order.Enable = checkBoxVisible.IsChecked == true ? Table.ProductS.EnumEnable.停用 : Table.ProductS.EnumEnable.启用;
            order.IsDiscount = checkBoxDiscount.IsChecked == true;
            order.IsScore = checkBoxScore.IsChecked == true;

            order.BaoXiu = integerUpDownBaoXiu.Value.HasValue ? integerUpDownBaoXiu.Value.Value : 0;
            order.Discount = doubleUpDownDiscount.Value.HasValue ? doubleUpDownDiscount.Value.Value : 0;

            order.Name = textBoxName.Text.Trim();
            order.Barcode = textBoxBarcode.Text;
            order.Standard = textBoxStandard.Text;
            order.Model = textBoxModel.Text;
            order.Note = textBoxNote.Text;
            order.Code = textBoxCode.Text;

            order.GroupSId = uCGroupS1.SelectedObjectId;
            order.UnitId = uCUniqueSUnit.SelectedObjectId;
            order.PlaceId = uCUniqueSPlace.SelectedObjectId;
            order.BrandId = uCUniqueSBrand.SelectedObjectId;

            order.PurchasePrice = doubleUpDownPurchasePrice.Value.Value;
            order.WholesalePrice1 = doubleUpDownWholesalePrice1.Value.Value;
            order.WholesalePrice2 = doubleUpDownWholesalePrice2.Value.Value;
            order.WholesalePrice3 = doubleUpDownWholesalePrice3.Value.Value;
            order.WholesalePrice4 = doubleUpDownWholesalePrice4.Value.Value;
            order.WholesalePrice5 = doubleUpDownWholesalePrice5.Value.Value;
            order.PosPrice = doubleUpDownPosPrice.Value.Value;
            order.VipPrice = doubleUpDownVip.Value.Value;

           // order._WuLiaoQingDan = (ObservableCollection<Table.ProductS>)productSListInfoWuLiao.ItemsSource;

            Table.DataTableS.EnumDatabaseStatus result = Table.DataTableS.EnumDatabaseStatus.操作成功;
            if (order.Id == -1)
                result = order.Insert();
            else
            {
                result = order.Update();
                foreach (StoreSProperty ssp in dataGridStoreS.ItemsSource)
                    Table.ProductSInStoreS.SetQuantityMaxAndMin(order.Id, ssp.Id, ssp.QuantityMax, ssp.QuantityMin);
            }

            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
            {
                if (string.IsNullOrEmpty(imageFile))
                    order.UploadFile = string.Empty;
                else
                    order.UploadFile = order.Id.ToString() + "_" + DateTime.Now.ToString(DbDefine.dateTimeFormat) + imageFile.Substring(imageFile.LastIndexOf('.'));

                order.UpdateImage();
                if (!string.IsNullOrEmpty(imageFile) && sendImageFile)
                {
                    FileFormat ff = new FileFormat()
                       {
                           FileFlag = FileType.传输文件,
                           IP = DoubleHConfig.AppConfig.ServerIP,
                           Port = DoubleHConfig.AppConfig.ServerPort.ToString(),
                           FilePath = imageFile,
                           TableName = "ProductS",
                           FileName = order.UploadFile
                       };

                    if (!TransferFiles.SaveFile(ff))
                        MessageWindow.Show("图片文件上传失败");
                }

                this.Close();
            }
            else
                MessageWindow.Show(result.ToString());
        }
    }
}